<template>
    <div class="page-saveAddress">
      <!-- 导航栏部分 -->
      <nav-bar :navbar-title="state === 0 ? '添加收货地址' :'修改收货地址'"></nav-bar>
      <div class="saveAddress-content">
        <!-- 收货地址表单信息部分 -->
        <div class="content-form">
            <div class="form-item">
                <span class="item-tip">收货人</span>
                <input class="item-input" type="text" v-model="addressForm.linkUser" placeholder="请填写收货人姓名">
            </div>
            <div class="form-item">
                <span class="item-tip">手机号码</span>
                <input class="item-input" type="text" v-model="addressForm.linkPhone" placeholder="请填写收货人手机号码">
            </div>
            <div class="form-item">
                <span class="item-tip">所在地区</span>
                <span v-if="addressForm.address_area === ''" class="item-text" @click="selectArea">请选择省/市/区(县)</span>
                <span v-else class="item-info" @click="selectArea">{{ addressForm.address_area }}</span>
            </div>
            <div class="form-item">
                <span class="item-tip">详细地址</span>
                <input class="item-input" type="text" v-model="addressForm.address_detail" placeholder="街道、楼牌号等信息">
            </div>
            <div class="form-item">
                <span class="item-tip">设为默认地址</span>
                <van-switch class="item-switch" v-model="addressForm.defaultAddress" size="22px"/>
            </div>
        </div>
        <!-- 保存并使用按钮 -->
        <div class="content-btns">
            <van-button class="btns-item" type="primary" @click="saveUserAddress_btn">保存并使用</van-button>
        </div>
      </div>
      <!-- vant4 pop弹出层 -->
      <van-popup :show="isShowAreaPop" position="bottom" :style="{ height: '50%' }">
        <van-area title="请选择省/市/区(县)" :area-list="areaList" @cancel="vanAreaCancel_btn" @confirm="vanAreaConfirm_btn"/>
      </van-popup>
    </div>
</template>

<script setup lang="ts">
//引入组合式vue
import { ref, reactive, onMounted } from "vue";
//@ts-ignore引入导航组件
import NavBar from "@/components/NavBar/NavBar.vue";
//引入vant组件
import { Icon, Button as VanButton, Switch as VanSwitch, Popup as VanPopup, Area as VanArea, showToast } from "vant";
import { areaList } from '@vant/area-data';
//@ts-ignore引入userStore仓库
import { useUserStore } from "@/store/userStore.ts";
const userStore = useUserStore();
//@ts-ignore引入请求函数
import { reqSaveAddress, reqUserAddress, reqUpdateAddress } from "@/api/user/index.ts";
//引入vue-router
import { useRoute, useRouter } from "vue-router";
const route = useRoute();
const router = useRouter();

//当前页的状态 0-添加收货地址 1-修改收货地址
let state = ref(0);
//地址区域选择pop弹出层开闭
let isShowAreaPop = ref(false);
//地址信息表单
const addressForm = reactive({
    linkUser:"",
    linkPhone:"",
    linkAddress:"",
    address_detail:"",
    address_area:"",
    defaultAddress:false
})

//选择省市区/县 文字按钮
function selectArea () {
    //打开pop弹出层
    isShowAreaPop.value = true;
}

//van-area地址选择的确定、取消事件
function vanAreaCancel_btn (selectInfo?:any) {
    //关闭pop弹出层
    isShowAreaPop.value = false;
}
function vanAreaConfirm_btn (selectInfo:any) {
    //获取到省市区(县)
    let areaStr = "";
    for(let i = 0; i < selectInfo.selectedOptions.length; i++){
        areaStr += (selectInfo.selectedOptions[i].text + " ");
    }
    addressForm.address_area = areaStr;
    //关闭pop弹出层
    vanAreaCancel_btn();
}

//保存并使用按钮
async function saveUserAddress_btn () {
    //参数整理
    const addressInfo = {userId:0,linkUser:addressForm.linkUser,linkPhone:addressForm.linkPhone,linkAddress:"",defaultAddress:addressForm.defaultAddress};
    addressInfo.linkAddress = addressForm.address_area.replaceAll(' ','') + addressForm.address_detail;
    addressInfo.userId = userStore.userInfo.id || JSON.parse(localStorage.getItem("userInfo")).id;
    //对参数进行校验判断
    if(addressInfo.userId === 0) return showToast({message:"用户id错误",position:"top"});
    if(addressInfo.linkUser.trim() === '') return showToast({message:"收货人姓名不能为空!",position:"top"});
    if(!Number(addressInfo.linkPhone) || addressInfo.linkPhone.length !== 11) return showToast({message:"请输入正确的手机号!",position:"top"});
    if(addressInfo.linkAddress.trim() === '') return showToast({message:"请输入收货地址!",position:"top"});
    //向服务器发起请求
    if(state.value === 0){
        //发请求保存新收货地址
        let res = await reqSaveAddress(addressInfo);
        if(res.code === 200){
            showToast({message:"地址添加成功!",position:"top"});
            //返回上一页
            setTimeout(() => {router.back();},500);
        }
        console.log("平台会员添加地址api",res);
    } else {
        //发请求更新收货地址信息
        addressInfo.id = route.query.id || 0;  //地址id不能少
        let res = await reqUpdateAddress(addressInfo);
        if(res.code === 200){
            showToast({message:"地址更新成功!",position:"top"});
            //返回上一页
            setTimeout(() => {router.back();},500);
        }
        console.log("平台会员更新地址api",res);
    }
}

//通过地址id获取地址信息
const getAddressInfo = async () => {
    let res = await reqUserAddress(route.query.id as any);
    if(res.code === 200){
        //赋值?考虑怎么从linkAddress截取出省市区(县)
        addressForm.linkUser = res.result.linkUser;
        addressForm.linkPhone = res.result.linkPhone;
        addressForm.linkAddress = res.result.linkAddress;
        addressForm.defaultAddress = res.result.defaultAddress;

        const regex = /^(.*?省|.*?自治区|.*?特别行政区)(.*?市|.*?自治州|.*?地区|.*?盟)(.*?区|.*?县|.*?市|.*?旗|.*?海域|.*?岛)/;
        const match = res.result.linkAddress.match(regex);
        if (match) {
            const province = match[1] || '';
            const city = match[2] || '';
            const district = match[3] || '';
            const detail = res.result.linkAddress.replace(province, '').replace(city, '').replace(district, '').trim();
            addressForm.address_area = province +" "+ city +" "+ district;
            addressForm.address_detail = detail;
        }

        showToast({message:"地址信息获取成功",position:"top"});
    }
    console.log('根据地址id获取平台会员收货地址信息api',res);
}

//vue生命周期
onMounted(() => {
    //获取当前路径是否含有参数，有参数则为修改地址信息(请求地址信息)，否则为添加地址信息
    if(route.query.id){
        state.value = 1;
        getAddressInfo();
    }
})
</script>

<style lang="less" scoped>
.page-saveAddress{
    width: 375px;
    .saveAddress-content{
        width: 375px;
        height: calc(100vh - 47px);
        position: relative;
        top:47px;
        background: #e4e7e9;
        display: flex;
        flex-direction: column;
        /**收货地址表单信息部分 */
        .content-form{
            width: 360px;
            margin: 10px auto;
            padding: 15px;
            box-sizing: border-box;
            background: #fff;
            display: flex;
            flex-direction: column;
            .form-item{
                width: 100%;
                height: 50px;
                display: flex;
                justify-content: space-between;
                align-items: center;
                border-bottom: 1px solid #e4e7e9;
                &:nth-last-child(1){
                    border-bottom: none;
                }
                .item-tip{
                    width: 100px;
                    font-size: 14px;
                    color: #000;
                }
                .item-input{
                    width: 230px;
                    height: 30px;
                    font-size: 14px;
                    line-height: 30px;
                    border: none;
                }
                .item-input::placeholder{
                    font-size: 12px;
                    color: #9195a3;
                }
                .item-text{
                    width: 230px;
                    font-size: 12px;
                    color: #9195a3;
                    cursor: pointer;
                }
                .item-info{
                    width: 230px;
                    font-size: 14px;
                    color: #000;
                    cursor: pointer;
                }
            }
        }
        .content-btns{
            width: 360px;
            margin: 20px auto;
            .btns-item{
                width: 360px;
                height: 45px;
            }
        }
    }
}
</style>